<?php
class Views {
	private $blocks = array();
	private $content = array();
	private $dataMap = array();
	
	public function addBlock($block) {
		$this->blocks[] = $block;
	}
	
	public function addContent($content) {
		$this->content[] = $content;
	}
	
	public function clearContent() {
		$content = array();
	}
	
	public function setVar($name,$value) {
		$this->dataMap[$name] = $value;
	}
	
	public function isContent() {
		return count($this->content) > 0;
	}
	
	public function render() {
		$httpResponse = new HTTPResponse();
		$httpResponse->monitor();
		
		$this->setVar('meta', $httpResponse->getMeta());
		$this->setVar('response', $this);
		
		$this->addBlock('status');
		
		// set data map
		foreach ($this->dataMap as $n=>$v) {
			global $$n;
			$$n = $v;
		}
		
		$sidebarContent = '';
		
		foreach ($this->blocks as $sidebar) {
			$viewname = VIEW . '/block.' . $sidebar . '.php';
			if (file_exists($viewname)) {
				ob_start();
				require $viewname;
				$sidebarContent .= ob_get_clean();
			}
		}
		
		$mainContent = '';
		
		foreach ($this->content as $c) {
			$viewname = VIEW . '/' . $c . '.tpl.php';
			if (file_exists($viewname)) {
				ob_start();
				require $viewname;
				$mainContent .= ob_get_clean();
			}
		}
		
		global $content, $sidebar;
		$content = $mainContent;
		$sidebar = $sidebarContent;
		
		require VIEW . '/layout.tpl.php';
		
		$httpResponse->unmonitor();
	}
}
